<template>
  <div>
    <el-form label-position="top">
      <el-form-item label="六、前期研究基础情况和支撑条件分析" />
      <el-form-item
        v-for="(item, key) in editors"
        :key="key"
        :label="item.title"
      >
        <div v-if="item.subTitle" class="sub-title">{{ item.subTitle }}</div>
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="item.editorRef"
            :default-config="toolbarConfig"
          />
          <Editor
            v-model="item.valueHtml"
            style="height: 400px; overflow-y: hidden"
            :default-config="editorConfig"
            @on-created="handleCreated($event, key)"
          />
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

  const $baseMessage = inject('$baseMessage')

  const editors = reactive({
    previousResearchBasis: {
      title: '（一）与本项目（课题）密切相关的前期研究基础情况',
      editorRef: null,
      valueHtml: '',
    },
    externalCooperationReasons: {
      title: '（二）与国内外合作研究及技术引进相结合的可能性',
      subTitle: '1.外协合作研究理由',
      editorRef: null,
      valueHtml: '',
    },
    externalCooperationUnits: {
      title: '2.外协合作研究单位及其在本领域的相关业绩及资质、研究基础',
      editorRef: null,
      valueHtml: '',
    },
    externalCooperationContent: {
      title: '3.外协合作研究内容、研究进度及成果指标',
      editorRef: null,
      valueHtml: '',
    },
    externalCooperationSupport: {
      title: '4.外协合作研究内容对本项目（课题）的支撑作用',
      editorRef: null,
      valueHtml: '',
    },
    externalCooperationBudget: {
      title: '5.外协经费测算',
      editorRef: null,
      valueHtml: '',
    },
    wellSiteSituation: {
      title: '（三）试验井位工程依托情况',
      editorRef: null,
      valueHtml: '',
    },
    intellectualPropertySearch: {
      title: '（四）与本项目（课题）有关的知识产权检索情况',
      editorRef: null,
      valueHtml: '',
    },
  })

  const toolbarConfig = {}
  const editorConfig = { placeholder: '请输入内容...' }

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    for (const key in editors) {
      const editor = editors[key].editorRef
      if (editor == null) return
      editor.destroy()
    }
  })

  const handleCreated = (editor, key) => {
    editors[key].editorRef = editor // 记录 editor 实例，重要！
  }

  const getFormData = () => {
    const params = {}
    for (const key in editors) {
      if (!editors[key].valueHtml) {
        $baseMessage('请填写完整的前期研究基础情况和支撑条件分析', 'error')
        return false
      }
      params[key] = editors[key].valueHtml
    }
    return params
  }

  const setFormData = (detailData) => {
    for (const key in editors) {
      editors[key].valueHtml = detailData.baseInfo[key]
    }
  }

  defineExpose({ getFormData, setFormData })
</script>

<style lang="scss" scoped></style>
